package com.llkj.contractmanagement.contractmanagement.mine;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.llkj.contractmanagement.contractmanagement.login.LoginActivity;
import com.llkj.contractmanagement.main.BaseActivity;
import com.llkj.contractmanagement.R;
import com.llkj.contractmanagement.customview.RoundImageView;
import com.llkj.contractmanagement.customview.SelectImageDialog;
import com.llkj.contractmanagement.customview.TitleBar;
import com.llkj.contractmanagement.http.Constant;
import com.llkj.contractmanagement.http.HttpMethod;
import com.llkj.contractmanagement.http.UrlConfig;
import com.llkj.contractmanagement.model.InfoBean;
import com.llkj.contractmanagement.model.UpdateLogoBean;
import com.llkj.contractmanagement.model.UserInfoBean;
import com.llkj.contractmanagement.utils.AppManager;
import com.llkj.contractmanagement.utils.DialogUtil;
import com.llkj.contractmanagement.utils.GsonUtil;
import com.llkj.contractmanagement.utils.ImageLoaderUtil;
import com.llkj.contractmanagement.utils.LogUtil;
import com.llkj.contractmanagement.utils.PicCameraLocalUtil;
import com.llkj.contractmanagement.utils.StringUtil;
import com.llkj.contractmanagement.utils.ToastUtil;
import com.llkj.contractmanagement.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import butterknife.Bind;
import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

/**
 * 用户资料
 * Created by zhu.px on 2016/6/12.
 */
public class UserInfoActivity extends BaseActivity implements View.OnClickListener, SelectImageDialog.ItemClickListener {
    @Bind(R.id.title_bar)
    TitleBar titleBar;
    @Bind(R.id.iv_photo)
    RoundImageView ivPhoto; //头像
    @Bind(R.id.rl_head)
    RelativeLayout rlHead;
    @Bind(R.id.tv_username)
    TextView tvUsername;  //姓名
    @Bind(R.id.rl_username)
    RelativeLayout rlUsername;
    @Bind(R.id.tv_gender)
    TextView tvGender; //性别
    @Bind(R.id.rl_gender)
    RelativeLayout rlGender;
    private UserInfoBean userInfoBean;
    private SelectImageDialog selectImageDialog;
    private File cameraFile;// 拍照文件
    private static final int REQUEST_CODE_USERNAME = 3;
    private Dialog genderDialog;
    private File userIconFile;//头像文件

    private String pic = "";
    private String name = "";
    private String date = "";
    private String gender = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_userinfo;
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        init();
        setListener();
    }

    private void init() {
        userInfoBean = UserInfoBean.getInstance();
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestInfo();
    }

    private void requestInfo() {
        HashMap<String, String> map = new HashMap<>();
        map.put("user_id", userInfoBean.getId());
        map.put("token", userInfoBean.getToken());
        HttpMethod.info(this, this, map, UrlConfig.HTTP_INFO);
    }


    private void setListener() {
        titleBar.setTopBarClickListener(this);
        rlHead.setOnClickListener(this);
        rlUsername.setOnClickListener(this);
        rlGender.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_username://姓名
                Intent intent = new Intent(this, UserNameActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_head://头像
                if (selectImageDialog == null) {
                    selectImageDialog = new SelectImageDialog(this, R.style.ActionSheetDialogStyle);
                    selectImageDialog.setItemClickListener(this);
                }
                selectImageDialog.show();
                break;
            case R.id.rl_gender://性别
                if (genderDialog == null) {
                    View view = getLayoutInflater().inflate(R.layout.dialog_choose_gender, null);
                    initView(view);
                    genderDialog = DialogUtil.showDialogBottom(this, view);
                }
                genderDialog.show();
                break;
            case R.id.btn_male:
                gender = "1";
                requestUpdateGenter();
                dismissDialog();
                break;
            case R.id.btn_female:
                gender = "2";
                requestUpdateGenter();
                dismissDialog();
                break;
            case R.id.dialog_cancel://取消
                dismissDialog();
                break;
        }
    }

    /*
    * 请求修改性别接口
    * */
    private void requestUpdateGenter() {
        HashMap<String, String> map = new HashMap<>();
    //        user_id	1	string	用户ID
    //        token	1	string	Token
    //        gender	1	string	性别（1 男 2女）
        map.put("user_id", userInfoBean.getId());
        map.put("token", userInfoBean.getToken());
        map.put("gender", gender);
        HttpMethod.updateGender(this, this, map, UrlConfig.HTTP_UPDATEGENDER);
    }

    private void dismissDialog() {
        if (genderDialog != null)
            genderDialog.dismiss();
    }

    private void initView(View view) {
        view.findViewById(R.id.btn_male).setOnClickListener(this);
        view.findViewById(R.id.btn_female).setOnClickListener(this);
        view.findViewById(R.id.dialog_cancel).setOnClickListener(this);
    }

    @Override
    public void album() {
        PicCameraLocalUtil.selectPicFromLocal(this);
    }

    @Override
    public void takephoto() {
        cameraFile = PicCameraLocalUtil.selectPicFromCamera(cameraFile, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case Constant.REQUEST_CODE_LOCAL://直接从相册获取
                if (data != null) {
                    Uri uri = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                    if (cursor != null) {
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex("_data");
                        String picturePath = cursor.getString(columnIndex);
                        cursor.close();
                        cursor = null;
                        if (picturePath != null && !picturePath.equals("null")) {
                            try {
                                uploadFile(PicCameraLocalUtil.revitionImageSize(picturePath, this));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        File file = new File(uri.getPath());
                        if (file.exists()) {
                            try {
                                uploadFile(PicCameraLocalUtil.revitionImageSize(file.getAbsolutePath(), this));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                break;
            case Constant.REQUEST_CODE_CAMERA://调用相机拍照
                if (cameraFile != null && cameraFile.exists()) {
                    Utils.startPhotoZoom(this, Uri.fromFile(cameraFile));
                }
                break;
            case Constant.PHOTORESOULT://裁剪后的照片
                if (data != null) {
                    setPicToView(data);
                }
                break;
        }
    }


    private void setPicToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            userIconFile = PicCameraLocalUtil.saveBitmap(this, photo);
            uploadFile(userIconFile);
        }
    }


    private void uploadFile(final File file) {
        if (!Utils.isNetworkConnected(this)) {
            ToastUtil.makeShortText(this, "请检查网络!");
            return;
        }
        String url = StringUtil.Utf8URLencode(UrlConfig.UPDATELOGO);
        Log.e("Log", "request::" + url);
        OkHttpUtils.post().url(UrlConfig.UPDATELOGO)
                .addFile("logo", "headImage.png", file)
                .addParams("user_id", userInfoBean.getId())
                .addParams("token", userInfoBean.getToken()).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
                dismissWaitDialog();
                ToastUtil.makeShortText(UserInfoActivity.this, "上传失败,请稍后再试");
                if (file != null && file.exists()) {
                    file.delete();
                }
            }

            @Override
            public void onResponse(String response) {
                Log.e("Log", "POST:" + response);
                dismissDialog();
                UpdateLogoBean updateLogoBean = GsonUtil.GsonToBean(response, UpdateLogoBean.class);
                if (updateLogoBean.getState() == 1) {
                    pic = updateLogoBean.getLogo();
                    ImageLoaderUtil.displayHeaderImage(pic, ivPhoto);
                    userInfoBean.setLogo(pic);
                    if (file != null && file.exists()) {
                        file.delete();
                    }
                } else {
                    ToastUtil.makeShortText(UserInfoActivity.this, updateLogoBean.getMessage());
                }
            }
        });
    }


    @Override
    public void onSuccessHttp(String responseInfo, int resultCode) {
        super.onSuccessHttp(responseInfo, resultCode);
        switch (resultCode) {
            case UrlConfig.HTTP_INFO://我的资料接口
                InfoBean infoBean = GsonUtil.GsonToBean(responseInfo, InfoBean.class);
                if (infoBean != null) {
                    if (infoBean.getState() == 1) {
                        ImageLoaderUtil.displayHeaderImage(infoBean.getLogo(), ivPhoto);
                        tvUsername.setText(infoBean.getName());
                        if (infoBean.getGender().equals("0")) {
                            tvGender.setText("");
                        } else if (infoBean.getGender().equals("1")) {
                            tvGender.setText("男");
                        } else if (infoBean.getGender().equals("2")) {
                            tvGender.setText("女");
                        }
                    }
                }
                break;
            case UrlConfig.HTTP_UPDATEGENDER://修改性别
                if (gender.equals("1")) {
                    tvGender.setText("男");
                    userInfoBean.setGender("1");
                } else if (gender.equals("2")) {
                    tvGender.setText("女");
                    userInfoBean.setGender("2");
                }
                break;
        }
    }

}
